<template>
  <el-form ref="form" :rules="rules" :model="form" label-width="80px">
    <el-form-item label="角色名称" prop="name">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="角色描述">
      <el-input v-model="form.description" />
    </el-form-item>
    <el-form-item class="box">
      <el-button @click="offFn">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { addRoleAPI, getRoleDetailAPI, updateRoleAPI } from '@/api/setting'
export default {
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    editId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  //   页面创建的时候,根据isEdit来判断是不是编辑,还是新增
  created() {
    if (this.isEdit === true) {
      console.log('编辑页面')
      this.getRoleDetailFn()
    }
    console.log(this.editId)
  },
  methods: {
    // 新增角色  一般来说调用接口都是有成功和失败,应该给用户一个提示
    async addRoleFn() {
      try {
        // 调用接口
        const res = await addRoleAPI(this.form)
        console.log(res)
        // 通知父组件关闭弹窗,刷新页面
        this.$emit('updateSett')
        this.$message({
          message: '添加成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('添加失败')
      }
    },
    // 点击编辑按钮数据回填
    async getRoleDetailFn() {
      const res = await getRoleDetailAPI(this.editId)
      console.log(res)
      this.form = res
    },
    // 点击确定,编辑资料完成
    async  updateRoleFn() {
      try {
        // 调用接口
        await updateRoleAPI({ ...this.form, id: this.editId })
        // 通知父组件关闭弹窗,刷新页面
        this.$emit('updateRole')
        this.$message({
          message: '编辑成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('编辑失败')
      }
    },
    // 点击确定按钮
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          alert('信息错误')
          return
        }
        this.isEdit === true ? this.updateRoleFn() : this.addRoleFn()
      })
    },
    offFn() {
      this.$emit('off')
    }
  }
}
</script>

<style scoped >
.box{
    text-align: center;
}
</style>
